package com.gz.mylife.app;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.util.PushUtils;
import com.gz.mylife.util.ToastUtils;
import com.loopj.android.http.RequestParams;
import com.tencent.connect.auth.QQAuth;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zl.smartmall.library.IGZAddress;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.account.LoginPlatform;
import com.zl.smartmall.library.account.po.CookieInfo;
import com.zl.smartmall.library.account.po.UserInfo;
import com.zl.smartmall.library.account.vo.CookieInfoDao;
import com.zl.smartmall.library.account.vo.UserInfoDao;
import com.zl.smartmall.library.concurrent.ThreadExecutor;
import com.zl.smartmall.library.listener.GetMyCommunityAddressListener;
import com.zl.smartmall.library.listener.PhoneRegisterListener;
import com.zl.smartmall.library.listener.RegisterCidListener;
import com.zl.smartmall.library.listener.RegisterTagListener;
import com.zl.smartmall.library.listener.UserInfoListener;
import com.zl.smartmall.library.listener.WechatAccessTokenListener;
import com.zl.smartmall.library.listener.WechatUserinfoListener;
import com.zl.smartmall.library.po.GZCommunityInfo;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.MD5;
import com.zl.smartmall.library.util.PreferenceModel;
import com.zl.smartmall.library.util.SingtonAsyncHttpClient;
import com.zl.smartmall.library.util.Tools;
import com.zl.smartmall.library.vo.GZCommunityInfoDAO;

public class Login extends BaseActivity implements OnClickListener {

	private static final String TAG = Login.class.getSimpleName();
	private IWXAPI mIwxapi;
	private QQAuth mQQAuth;
	private com.tencent.connect.UserInfo mQQUserInfo;
	private Tencent mTencent;
	private UserInfoListener mUserInfoListener;
	private RegisterCidListener mRegisterCidListener;
	private RegisterTagListener mRegisterTagListener;
	private WechatAccessTokenListener mWechatAccessTokenListener;
	private WechatUserinfoListener mWechatUserinfoListener;
	private WechatAuthReceiver mWeChatAuthReceiver;

	private EditText mEtPhone;
	private EditText mEtPassword;
	private Dialog mLoadingData;
	private MyHandler mHandler;
	private MyPhoneRegisterListener mListener;
	private MyGetCommunityListener mGetcommunityListener;


	private BaseUiListener baseUiListener=new BaseUiListener();


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		mIwxapi = WXAPIFactory.createWXAPI(getApplicationContext(), Define.APP_ID_WECHAT, true);
		mQQAuth = Global.getInstance().getQQAuth();
		mTencent = Tencent.createInstance(Define.APP_ID_QQ,getApplicationContext());
		logQQAuth();
		initListener();
		mWeChatAuthReceiver = new WechatAuthReceiver();
		IntentFilter filter = new IntentFilter(Define.ACTION_WECHAT_AUTH_SUCCESS);
		registerReceiver(mWeChatAuthReceiver, filter);

		mGetcommunityListener = new MyGetCommunityListener(this);

		mHandler = new MyHandler(this);
		mListener = new MyPhoneRegisterListener(this);

		mEtPhone = (EditText) findViewById(R.id.et_phone);
		mEtPassword = (EditText) findViewById(R.id.et_password);
		mLoadingData = new Dialog(this, R.style.DialogTheme);
		mLoadingData.setContentView(R.layout.loading_data_dialog2);
		mLoadingData.setCanceledOnTouchOutside(false);

		findViewById(R.id.btn_qq_login).setOnClickListener(this);
		findViewById(R.id.btn_wechat_login).setOnClickListener(this);
		findViewById(R.id.tv_register).setOnClickListener(this);
		findViewById(R.id.tv_forget_password).setOnClickListener(this);
		findViewById(R.id.btn_login).setOnClickListener(this);
		//		mActionBar.setTitle("登录");
		setActionbarTitle("双明汇", false);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mWeChatAuthReceiver);
		mGetcommunityListener.release();
		if(mLoadingData.isShowing()) {
			mLoadingData.dismiss();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_qq_login:
			mLoadingData.show();
			//			IUiListener listener = new BaseUiListener();
			//			mTencent.login(this, "all", listener);
			mTencent.login(Login.this, "all", baseUiListener);

			break;
		case R.id.tv_register:
			Intent registerIntent = new Intent(getApplicationContext(), Register1.class);
			registerIntent.putExtra("type", 0);
			startActivity(registerIntent);
			break;
		case R.id.tv_forget_password:
			Intent fpIntent = new Intent(getApplicationContext(), Register1.class);
			fpIntent.putExtra("type", 1);
			startActivity(fpIntent);
			break;
		case R.id.btn_login:
			String str = mEtPhone.getText().toString();

			if(TextUtils.isEmpty(str)){
				Toast.makeText(this, "请输入您的手机号码", Toast.LENGTH_SHORT).show();
				break;
			}
			if(!Tools.checkPhone(str)){
				Toast.makeText(this, "您的手机号码输入有误", Toast.LENGTH_SHORT).show();
				break;
			}

			if(TextUtils.isEmpty(mEtPassword.getText().toString())){
				Toast.makeText(this, "请输入您的密码", Toast.LENGTH_SHORT).show();
				break;
			}

			mLoadingData.show();
			loginAsPhone();
			break;

		case R.id.btn_wechat_login:
			//			mLoadingData.show();
			//			SendAuth.Req req = new SendAuth.Req();
			//			req.scope = "snsapi_userinfo";
			//			req.state = "wechat_login" + new Random().nextInt(100);
			//			mIwxapi.sendReq(req);

			//以上原来写法
			mLoadingData.show();
			weixinlogin();

			break;

		default:
			break;
		}
	}

	private void loginAsPhone() {
		if (!Tools.hasInternetConnection(getApplicationContext())) {
			mLoadingData.dismiss();
			Toast.makeText(this, Define.MSG_NO_NETWORK, Toast.LENGTH_SHORT)
			.show();
			return;
		}
		String url = Constants.URL_PHONE_LOGIN;
		RequestParams params = new RequestParams();
		final String imei =Tools.getIMEI(getApplicationContext());
		final String mac;
		String macAddress = Tools.getLocalMacAddress(getApplicationContext());
		if(TextUtils.isEmpty(macAddress)){
			mac = imei;
		} else {
			mac = macAddress;
		}
		final String alias =MD5.md5(imei+mac);
		final long localDatetime = System.currentTimeMillis()/1000;
		final String appver =Tools.getAppVersionName(getApplicationContext());
		String discuzId = "";

		params.put("mac", mac);
		params.put("imei", imei);
		params.put("devicetime", localDatetime+"");
		params.put("alias", alias);
		params.put("bundleID", "");
		params.put("jutt", 0);  //0为uid，1为md5(uid_mac)
		params.put("discuz_id", discuzId);
		params.put("username", mEtPhone.getText().toString());
		params.put("password", MD5.md5(mEtPassword.getText().toString()));

		SingtonAsyncHttpClient.getInstance().post(url, params, mListener);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(mTencent != null) {
			//mTencent.onActivityResult(requestCode, resultCode, data);
			//Tencent.onActivityResultData(requestCode,resultCode,data,baseUiListener);
		}
	}

	private void initListener() {
		mUserInfoListener = new UserInfoListener() {

			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				mLoadingData.dismiss();
				ToastUtils.showToast(getApplicationContext(), Define.MSG_LOGIN_FAILED);
			}

			@Override
			public void onResponseSuccess(UserInfo userinfo) {
				// TODO Auto-generated method stub
				//				if(userinfo != null) {
				//					CrashHandler.d(TAG, Define.MSG_LOGIN_SUCCESS);
				//					IAuth.getInstance().registerCID(PreferenceModel.getString(Define.PREFERENCE_KEY_CID, ""), mRegisterCidListener);
				//					IAuth.getInstance().registerTAG(PushUtils.buildTag(getApplicationContext()), mRegisterTagListener);
				//					startActivity(new Intent(getApplicationContext(), Plaza.class));
				//					finish();
				//				}
				mHandler.sendEmptyMessage(1);
			}

			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), Define.MSG_NO_NETWORK);
				mLoadingData.dismiss();
			}
		};

		mRegisterCidListener = new RegisterCidListener() {

			int reqCount;

			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				if(reqCount < 5) {//失败重试5次
					reqCount++;
					IAuth.getInstance().registerCID(PreferenceModel.getString(Define.PREFERENCE_KEY_CID, ""), this);
				}
			}

			@Override
			public void onOffline() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				CrashHandler.d(TAG, "CID注册成功");
			}
		};

		mRegisterTagListener = new RegisterTagListener() {

			int reqCount;

			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				if(reqCount < 5) {//失败重试5次
					reqCount++;
					IAuth.getInstance().registerTAG(PushUtils.buildTag(getApplicationContext()), mRegisterTagListener);
				}
			}

			@Override
			public void onOffline() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				CrashHandler.d(TAG, "TAG注册成功");
			}
		};

		mWechatAccessTokenListener = new WechatAccessTokenListener() {

			@Override
			public void onResponseSuccess(int expiresIn, String accessToken,
					String openId, String refreshToken, String scope) {
				// TODO Auto-generated method stub
				mWechatUserinfoListener.setAccessToken(accessToken);
				IAuth.getInstance().getWeChatUserInfo(accessToken, openId, mWechatUserinfoListener);
			}

			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				mLoadingData.dismiss();
				ToastUtils.showToast(getApplicationContext(), Define.MSG_LOGIN_FAILED);
			}

			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				mLoadingData.dismiss();
				ToastUtils.showToast(getApplicationContext(), Define.MSG_LOGIN_FAILED);
			}
		};

		mWechatUserinfoListener = new WechatUserinfoListener() {

			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				CrashHandler.d(TAG, "获取微信用户资料失败");
				mLoadingData.dismiss();
				ToastUtils.showToast(getApplicationContext(), Define.MSG_LOGIN_FAILED);
			}

			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				mLoadingData.dismiss();
				ToastUtils.showToast(getApplicationContext(), Define.MSG_LOGIN_FAILED);
			}

			@Override
			public void onResponseSuccess(int sex, String nickname, String province,
					String city, String country, String headImgUrl, String openId,
					String unionid, String accessToken) {
				// TODO Auto-generated method stub
				if(nickname !=null && nickname.length() > 12){
					nickname.substring(0, 12);
				}
				IAuth.getInstance().login(
						LoginPlatform.WECHAT,
						accessToken, 
						openId, 
						nickname, 
						headImgUrl, 
						String.valueOf(sex), 
						mUserInfoListener);

				CrashHandler.d(TAG, "昵称" + nickname);
				CrashHandler.d(TAG, "性别" + sex);
				CrashHandler.d(TAG, "头像" + headImgUrl);
				CrashHandler.d(TAG, "accessToken = " + accessToken);
				CrashHandler.d(TAG, "openId = " + openId);
			}
		};
	}

	private void logQQAuth() {
		CrashHandler.d(TAG, "access token = " + mQQAuth.getQQToken().getAccessToken());
		CrashHandler.d(TAG, "openId = " + mQQAuth.getQQToken().getOpenId());
		CrashHandler.d(TAG, "time = " + mQQAuth.getQQToken().getExpireTimeInSecond());
	}

	private void LoginQQSuccess(JSONObject response) {
		if (mQQAuth != null && mQQAuth.isSessionValid()) {
			IUiListener listener = new IUiListener() {

				@Override
				public void onError(UiError e) {
					// TODO Auto-generated method stub
					CrashHandler.d(TAG, e.errorDetail);
				}

				@Override
				public void onComplete(final Object obj) {
					try {
						JSONObject response = (JSONObject)obj;
						String nickname = response.getString("nickname");
						String gender = response.getString("gender");
						String face = response.getString("figureurl_qq_2");
						if (TextUtils.isEmpty(face)) {
							face = response.getString("figureurl_qq_1");
						}

						//						loginServerWithQQ(mQQAuth.getQQToken().getAccessToken(), face, 
						//								gender, nickname, mQQAuth.getQQToken().getOpenId());
						IAuth.getInstance().login(
								LoginPlatform.QQ,
								mQQAuth.getQQToken().getAccessToken(), 
								mQQAuth.getQQToken().getOpenId(), 
								nickname, face, gender, mUserInfoListener);

						CrashHandler.d(TAG, "昵称" + nickname);
						CrashHandler.d(TAG, "性别" + gender);
						CrashHandler.d(TAG, "头像" + face);
						logQQAuth();


					} catch(Exception e) {
						CrashHandler.e(e);
					}
				}

				@Override
				public void onCancel() {
					// TODO Auto-generated method stub
					CrashHandler.d(TAG, "登录取消");
					mLoadingData.dismiss();
				}
			};
			//			  MainActivity.mTencent.requestAsync(Constants.GRAPH_SIMPLE_USER_INFO, null,
			//	                    Constants.HTTP_GET, requestListener, null);
			mQQUserInfo = new com.tencent.connect.UserInfo(this, mQQAuth.getQQToken());
			mQQUserInfo.getUserInfo(listener);

		}
	}

	private class BaseUiListener implements IUiListener {

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			ToastUtils.showToast(Login.this, "登录已取消");
			mLoadingData.dismiss();
		}

		@Override
		public void onComplete(Object response) {
			// TODO Auto-generated method stub
			LoginQQSuccess((JSONObject) response);
			Log.i("qwer", "成功：="+response.toString().trim());
		}

		@Override
		public void onError(UiError err) {
			// TODO Auto-generated method stub
			ToastUtils.showToast(Login.this, "登录失败, 请重新登录");
			mLoadingData.dismiss();
		}

	}

	private class WechatAuthReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			CrashHandler.d(TAG, "微信授权成功广播");
			IAuth.getInstance().getWeChatAccessToken(intent.getStringExtra("code"), 
					Define.APP_ID_WECHAT, Define.APP_SECRET_WECHAT, mWechatAccessTokenListener);
		}
	};

	private static class MyPhoneRegisterListener extends PhoneRegisterListener{
		private Login mOuter;
		public MyPhoneRegisterListener(Login outer){
			this.mOuter = outer;
		}

		public void release(){
			new WeakReference<Login>(mOuter);
		}

		@Override
		public void onSmsCodeError() {
			if(mOuter == null){
				return;
			}
			mOuter.mLoadingData.dismiss();
			Toast.makeText(mOuter.getApplicationContext(), "您输入的账户或者密码有误", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onResponseFailed() {
			// TODO Auto-generated method stub
			if(mOuter == null){
				return;
			}
			mOuter.mLoadingData.dismiss();
			Toast.makeText(mOuter.getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onResponseSuccess(CookieInfo cookieInfo, UserInfo userinfo) {
			// TODO Auto-generated method stub
			if(mOuter == null){
				return;
			}
			mOuter.saveToDB(cookieInfo, userinfo);
		}

		@Override
		public void onNoNetWork() {

		}

	}

	private void saveToDB(final CookieInfo cookieInfo,final UserInfo userInfo){
		ThreadExecutor.getInstance().execute(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					//存储cookie
					if(cookieInfo != null) {
						CookieInfoDao cookieInfoDao = new CookieInfoDao(getApplicationContext());
						cookieInfoDao.delete();
						cookieInfoDao.insert(cookieInfo);
					}

					PreferenceModel.putInt(Constants.PREFERENCE_KEY_UID, userInfo.getUid());
					//					PreferenceModel.putString(Constants.PREFERENCE_KEY_TOKEN, userInfo.getToken());
					PreferenceModel.putString(Constants.PREFERENCE_KEY_LOGIN_PLATFORM, userInfo.getLoginPlatform());
					UserInfoDao userInfoDao = new UserInfoDao(getApplicationContext());
					userInfoDao.delete();
					userInfoDao.insert(userInfo);
					mHandler.sendEmptyMessage(1);


				} catch (JSONException e) {
					CrashHandler.e(e);
				}
			}
		});
	}

	private static class MyHandler extends Handler{
		private Login mOuter;

		public MyHandler(Login outer){
			this.mOuter = outer;
		}
		public void release(){
			new WeakReference<Login>(mOuter);
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				IGZAddress.getInstance().getMyCommunity(mOuter.mGetcommunityListener);
				break;
			case 2:
				UserInfo userinfo = IAuth.getInstance().loadUserInfo();
				if(userinfo != null) {
					IAuth.getInstance().registerCID(PreferenceModel.getString(Define.PREFERENCE_KEY_CID, ""), mOuter.mRegisterCidListener);
					IAuth.getInstance().registerTAG(PushUtils.buildTag(mOuter.getApplicationContext()), mOuter.mRegisterTagListener);
					Intent exit = new Intent(Define.ACTION_EXIT_WHOLE_APP);
					mOuter.sendBroadcast(exit);
					//					//startActivity(new Intent(Login.this, MainTab.class));
					mOuter.startActivity(new Intent(mOuter.getApplicationContext(), Plaza.class));
					//					mOuter.mLoadingData.dismiss();
				}
				break;

			default:
				break;
			}
		}
	}


	private static class MyGetCommunityListener extends GetMyCommunityAddressListener {
		private Login mOuter;
		private MyGetCommunityListener(Login outer){
			this.mOuter = outer;
		}

		public void release(){
			new WeakReference<Login>(mOuter);
		}

		@Override
		public void onResponseSuccess(final List<GZCommunityInfo> lists) {
			ThreadExecutor.getInstance().execute(new Runnable() {

				@Override
				public void run() {
					GZCommunityInfoDAO.DeleteAll(mOuter.getApplicationContext());
					GZCommunityInfoDAO.saveAll(mOuter.getApplicationContext(), lists);
				}
			});
			mOuter.mHandler.sendEmptyMessage(2);
		}

		@Override
		public void onNoMoreData() {
			mOuter.mHandler.sendEmptyMessage(2);
		}

		@Override
		public void onNoNetWork() {
			mOuter.mHandler.sendEmptyMessage(2);
		}

		@Override
		public void onOffline() {
			mOuter.mHandler.sendEmptyMessage(2);
		}

		@Override
		public void onResponseFailed() {
			mOuter.mHandler.sendEmptyMessage(2);
		}

	}


	/**
	 * 微信登录
	 */
	public void weixinlogin(){
		UMShareAPI.get(Login.this).doOauthVerify(Login.this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
			@Override
			public void onStart(SHARE_MEDIA share_media) {

			}

			@Override
			public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
				Log.i("chenghao","登陆成功:"+map.toString());
				//获取授权成功后,开始获取用户信息
				UMShareAPI.get(Login.this).getPlatformInfo(Login.this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
					@Override
					public void onStart(SHARE_MEDIA share_media) {

					}
					@Override
					public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
						Log.i("chenghao","map="+map.toString());
						Log.i("chenghao","name="+map.get("name"));
						Log.i("chenghao","access_token="+map.get("access_token"));
						Log.i("chenghao","profile_image_url="+map.get("profile_image_url"));
						Log.i("chenghao","openid="+map.get("openid"));
						Log.i("chenghao","gender="+map.get("gender"));
						//获取了信息,开始走自己的登陆接口了
						
						
						IAuth.getInstance().login(
								LoginPlatform.WECHAT,
								map.get("access_token"), 
								map.get("openid"), 
								map.get("name"), 
								map.get("profile_image_url"), 
								map.get("gender"), 
								mUserInfoListener);
						
					}
					@Override
					public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
						Toast.makeText(Login.this, "失败：" + throwable.getMessage(),Toast.LENGTH_LONG).show();
					}
					@Override
					public void onCancel(SHARE_MEDIA share_media, int i) {
						Toast.makeText(Login.this, "取消了", Toast.LENGTH_LONG).show();
					}
				});
			}

			@Override
			public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
				Toast.makeText(Login.this, "失败：" + throwable.getMessage(), Toast.LENGTH_LONG).show();
			}

			@Override
			public void onCancel(SHARE_MEDIA share_media, int i) {
				Toast.makeText(Login.this, "取消了", Toast.LENGTH_LONG).show();
			}
		});
	}




}
